package com.ztjava.auth.controller.member.weixin;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Duang;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.auth.Auth;
import com.ztjava.auth.model.AuthThird;
import com.ztjava.auth.model.AuthUser;
import com.ztjava.auth.service.AuthService;
import com.ztjava.core.Constant;
import com.ztjava.core.Jsub;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.client.member.MobileClient;
import com.ztjava.core.tool.ViewTool;
import com.ztjava.core.utiliy.RequestUtil;
import com.ztjava.ext.auth.annotation.UserController;
import com.ztjava.ext.auth.tool.AuthTool;
import com.ztjava.plugin.weixin.WeixinKit;
import com.ztjava.plugin.weixin.WeixinSdk;

@ControllerClass(path="/auth/weixin",client=MobileClient.class)
@UserController(portal=Constant.P_MEMBER)
public class AuthMobileWeixinController extends BaseController {
	private static AuthService authService = Duang.duang(AuthService.class);

	/***
	 * 微信公众号登录
	 * @throws Exception
	 */
	public void login() throws Exception{
		if(ViewTool.param("AUTH_MEMBER_THIRD_WEIXIN_ONOFF","OFF").equals("OFF")){
			renderHtml("未启用微信公众号登录！");
			return;
		}
		String redirect = getPara("redirect",Jsub.path+getAttrForStr(Constant.PRE_PATH)+"/auth/index");
		String checkUrl = RequestUtil.getDomain(getRequest())+Jsub.path+getAttrForStr(Constant.PRE_PATH)+"/auth/weixin/doLogin";
		
		WeixinSdk weixinSdk = WeixinKit.use();
		redirect(weixinSdk.auth2_login(checkUrl, redirect, getPara("scope","snsapi_userinfo")));
	}
	/***
	 * 微信公众号登录验证
	 * @throws Exception
	 */
	public void doLogin() throws Exception{
		keepPara();
		Cache cache = Redis.use();
		String state = getPara("state");
		String code = getPara("code","");
		if(!cache.exists(Constant.R_PRE+"WEIXINSDK:STATE:"+state)){
			setAttr(Constant.MESSAGE, "页面授权已过期，请重新打开");
			render("error.html");
			return;
		}
		WeixinSdk weixinSdk = WeixinKit.use();
		Ret authAccessToken = weixinSdk.auth2_access_token(code);
		if(authAccessToken.getStr(Constant.RESULT).equals(Constant.ERROR)){
			setAttr(Constant.MESSAGE, authAccessToken.getStr(Constant.MESSAGE));
			render("error.html");
			return;
		}
		String redirect = cache.hget(Constant.R_PRE+"WEIXINSDK:STATE:"+state,"redirect");
		String scope = cache.hget(Constant.R_PRE+"WEIXINSDK:STATE:"+state,"scope");
		String openid = authAccessToken.getStr("openid");
		if(!scope.equals("snsapi_userinfo")){
			//只是为了获取openid
			setSessionAttr("AUTH_WEIXIN_OPENID", openid);
			cache.del(Constant.R_PRE+"WEIXINSDK:STATE:"+state);
			renderRedirect(redirect);
			return;
		}
		
		//身份验证
		AuthThird authThird = authService.getThirdByCode(Constant.P_MEMBER,AuthThird.WEIXIN, openid);
		//已绑定会员
		if(authThird.get("user_id")!=null){
			AuthUser authUser = AuthUser.dao.findById(authThird.getInt("user_id"));
			if(authUser==null||authUser.getStr("enable_flag").equals("F")){
				setAttr(Constant.MESSAGE, "账户被删除或被停用！");
				render("error.html");
				return;
			}
			//微信支付可能用的着
			cache.hset(Constant.R_PRE+"AUTH:THIRD:WEIXIN", authUser.getInt("id"), openid);
			
			AuthTool.createUserSession(authService.userToSession(authUser)
					,3600 * 24* 7, getResponse(),null);

			authThird.set("last_login_time", new Timestamp(new Date().getTime())).update();
			
			cache.del(Constant.R_PRE+"WEIXINSDK:STATE:"+state);
			renderRedirect(redirect);
			return;
		}
		//未绑定会员
		if(!ViewTool.param("AUTH_"+Constant.P_MEMBER+"_REGISTER_ONOFF").equals("ON")){
			setAttr(Constant.MESSAGE, "已停止注册！");
			render("error.html");
			return;
		}
		//获取用户详细信息
		Ret userInfo = weixinSdk.auth2_userinfo(openid,authAccessToken.getStr("access_token"));
		if(userInfo.getStr(Constant.RESULT).equals(Constant.ERROR)){
			setAttr(Constant.MESSAGE,userInfo.getStr(Constant.MESSAGE));
			render("error.html");
			return;
		}

		Map<String,String> userMap = new HashMap<>();
		userMap.put("name", userInfo.getStr("nickname"));
		userMap.put("headimg", userInfo.getStr("headimgurl"));
		if(userInfo.get("unionid")!=null){
			authThird.set("unionid", userInfo.getStr("unionid")).update();
		}
		switch (ViewTool.param("AUTH_MEMBER_THIRD_AUTHTYPE")) {
			case "AUTO":
				AuthUser authUser = authService.insertUserByThird(authThird,userMap);
				//微信支付会用的
				cache.hset(Constant.R_PRE+"AUTH:THIRD:WEIXIN", authUser.getInt("id"), openid);
				
				AuthTool.createUserSession(authService.userToSession(authUser),
						3600 * 24 * 7,getResponse(),null);

				cache.del(Constant.R_PRE+"WEIXINSDK:STATE:"+state);
				renderRedirect(redirect);
				return;
			case "BINDING":
				setSessionAttr(Auth.SESSION_THIRD_ID, authThird.getInt("id"));
				setSessionAttr(Auth.SESSION_THIRD_USER, userInfo);
				
				cache.del(Constant.R_PRE+"WEIXINSDK:STATE:"+state);
				renderRedirect(Jsub.path+getAttrForStr(Constant.PRE_PATH)+"/auth/binding?redirect="+redirect);
				return;
			default:
				break;
		}
		setAttr(Constant.MESSAGE,"没有可用的处理方式！");
		render("error.html");
		return;
	}
	
}
